﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace vorkos_dev_snake
{
    public class Menu
    {
        private static readonly Object s_lock = new Object();
        private static Menu instance = null;
        public static Menu Instance
        {
            get
            {
                if (instance != null) return instance;
                Monitor.Enter(s_lock);
                Menu temp = new Menu();
                Interlocked.Exchange(ref instance, temp);
                Monitor.Exit(s_lock);
                return instance;
            }
        }

        private Menu()
        {
        }

        [Serializable]
        private class Container
        {
            public Snake SnakePersonage { get; set; }
            public Field CurrentField { get; set; }
            public GameLogic GameLogicInstance { get; set; }
        }
        public void CallMenu(Snake snakePersonage, Field currentField, GameLogic gameLogicInstance)
        {
            Container state = new Container()
            {
                SnakePersonage = snakePersonage,
                CurrentField = currentField,
                GameLogicInstance = gameLogicInstance
            };
            Serialize(state);
            GameLogic.Instance.UI.DrawMenu();
            Deserialize();
        }
        public void CallStartMenu()
        {
            Deserialize();
        }

        private void Deserialize()
        {
            Container state = new Container();
            using (FileStream fs = new FileStream("DataFile.dat", FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                state = (Container)formatter.Deserialize(fs);
                state.GameLogicInstance.UI.KeyPressed += state.GameLogicInstance.UI_KeyPressed;
            }
        }
        private void Serialize(Container state)
        {
            state.GameLogicInstance.UI.KeyPressed -= state.GameLogicInstance.UI_KeyPressed;
            BinaryFormatter formatter = new BinaryFormatter();
            using (FileStream fs = new FileStream("DataFile.dat", FileMode.Create))
            {
                formatter.Serialize(fs, state);
            }
        }
    }

}
